/*
 * Copyright (c) 2010 All Inclusive Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.eastchina.fids2focs.common.interceptor;

import java.text.MessageFormat;

import javax.servlet.http.HttpSession;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.xfire.transport.http.XFireServletController;

import com.eastchina.fids2focs.common.GlobalConstants;
import com.eastchina.fids2focs.domain.SystemUser;


/**
 * 日志出力拦截器
 * 
 * @author xyg
 *
 */
public class LoggingInterceptor implements MethodInterceptor {

    /**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 738414089087306512L;

	/**
	 * 日志出力对象
	 */
	private static final Log log = LogFactory.getLog(LoggingInterceptor.class);
    
	/**
	 * 日志出力形式
	 */
    protected static final MessageFormat format = new MessageFormat("Sessionid:{0} Username:{1} Service:{2} (method:{3}) start!");
    protected static final MessageFormat endFormat = new MessageFormat("Sessionid:{0} Username:{1} Service:{2} (method:{3}) end! [execute time :{4}ms]");
    
    /**
     * 操作日志出力
     */
	public Object invoke(MethodInvocation invoker) throws Throwable {
		
		// FIXME
		long start = System.currentTimeMillis();
		
		// 获取登录用户信息
		HttpSession session = XFireServletController.getRequest().getSession();
		SystemUser userObject = (SystemUser) session.getAttribute(GlobalConstants.USER_KEY);
		// 操作日志出力
		log.info(format.format(new Object[]{
				session.getId(),
				userObject == null ? null : userObject.getLoginId(),
				invoker.getThis().getClass().getSimpleName(),
				invoker.getMethod().getName()
		}));

		if (log.isDebugEnabled()) {
			log.debug("arguments:" + ToStringBuilder.reflectionToString(invoker.getArguments()));
		}		
		Object obj = invoker.proceed();
		if (log.isDebugEnabled()) {
			log.debug("result:" + ToStringBuilder.reflectionToString(obj));
		}
		
		// FIXME
		long end = System.currentTimeMillis();		
		log.info(endFormat.format(new Object[]{
				session.getId(),
				userObject == null ? null : userObject.getLoginId(),
				invoker.getThis().getClass().getSimpleName(),
				invoker.getMethod().getName(),
				(end - start)
		}));
		
		return obj;
	}
}
